import axios from 'axios'
import { Message} from 'element-ui';
import store from '../store'
import router from '../router'

// axios 配置
const axiosInstance = axios.create({
    baseURL: process.env.API_HOST,
    timeout: 10000,
    headers:{
        // "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"
        "Content-Type":"application/json;charset=UTF-8"
    }
})

// http request 拦截器
axiosInstance.interceptors.request.use(
    config => {
        if (!!store.state.users.currentUser.UserToken) config.headers.Authorization = 'bearer ' + store.state.users.currentUser.UserToken;
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axiosInstance.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面

                    store.commit('users/clearUser');
                    router.replace({
                        path: '/login',
                        query: {redirect: router.currentRoute.fullPath}
                    });
                    break;
                case 403:
                    // 403 无权限，跳转到首页

                    router.replace({
                        path: '/',
                        query: {redirect: router.currentRoute.fullPath}
                    });
                    break;
            }
        }
        return Promise.reject(error);
    });


export default {
    /*
    * get请求
    * @returns {Promise}
    */
    get(url,params={},config={showLoading: true}){
        config.params = params;
        return axiosInstance.get(url,config)
    },

    /*
    * post请求
    * @returns {Promise}
    */
    post(url,data={},config={showLoading: true,isForm: false}){
        if(config.isForm) config.headers = {'Content-Type':'multipart/form-data'};
        return axiosInstance.post(url,data,config)
    },


    put(url,data,config){
        config.headers = {'Content-Type':'multipart/form-data'};
        return axiosInstance.put(url,data,config)
    }
}

 
  


